package com.bwie.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.*;
import com.bwie.pojo.*;
import com.bwie.service.TbProdService;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtil;
import com.bwie.vo.PageInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Lenovo
* @description 针对表【tb_prod(商品表)】的数据库操作Service实现
* @createDate 2025-07-19 08:43:08
*/
@Service
@Slf4j
public class TbProdServiceImpl extends ServiceImpl<TbProdMapper, TbProd>
    implements TbProdService{

    @Autowired
    TbProdMapper tbProdMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    TbTypeMapper tbTypeMapper;
    @Autowired
    TbDictMapper tbDictMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    TbProdAttaMapper tbProdAttaMapper;
    @Autowired
    TbProdInfoMapper tbProdInfoMapper;

    @PostConstruct
    public void loadDictList(){
        log.info("开始加载字典表数据");

        List<TbDict> tbDictList = tbDictMapper.selectList(null);

        for (TbDict tbDict : tbDictList) {
            String key1 = "dict-" + tbDict.getDictType();
            String key2 = tbDict.getDictValue()+"";

            stringRedisTemplate.opsForHash().put(key1,key2, JSON.toJSONString(tbDict));
        }

        log.info("加载字典表数据结束");
    }

    @Override
    public R getProdList(PageInfoVo pageInfoVo) {
        Page<TbProd> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        Page<TbProd> tbProdPage = tbProdMapper.getProdList(page, pageInfoVo);

        return R.OK(tbProdPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteBatch(List<Integer> ids) {
        if(ids==null || ids.size()==0){
            return R.ERROR(404,"请选择要删除的数据");
        }
        tbProdMapper.deleteBatchIds(ids);

        tbProdAttaMapper.delete(
                new LambdaQueryWrapper<TbProdAtta>().in(TbProdAtta::getProdId,ids)
        );
        return R.OK();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteProd(Integer prodId) {
        TbProd tbProd = tbProdMapper.selectById(prodId);
        if(tbProd == null){
            return R.ERROR(404,"该商品不存在");
        }

        tbProdMapper.deleteById(prodId);
        tbProdAttaMapper.delete(
                new LambdaQueryWrapper<TbProdAtta>().eq(TbProdAtta::getProdId,tbProd.getProdId())
        );
        return R.OK();
    }

    @Override
    public R getTypeInfo() {
        List<TbType> tbTypeList = tbTypeMapper.selectList(null);
        List<Tree<String>> treeList = TreeUtil.build(tbTypeList, "0", (type, tree) -> {
            tree.setId(type.getTypeId()+"");
            tree.putExtra("value",type.getTypeId());
            tree.putExtra("label",type.getTypeName());
            tree.putExtra("typeId",type.getTypeId());
            tree.putExtra("typeName",type.getTypeName());
            tree.setParentId(type.getTypePid() + "");
            tree.putExtra("typeImage", type.getTypeImage());
            tree.putExtra("typeTop", type.getTypeTop());
            tree.putExtra("typeStatus", type.getTypeStatus());
        });
        return R.OK(treeList);
    }

    @Override
    public R getDictList(Integer typeId) {
        String key = "dict-"+typeId;
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if(hasKey){
            System.out.println("从缓存中读取字典列表");
            List<Object> values = stringRedisTemplate.opsForHash().values(key);
            List<TbDict> tbDictList = values.stream().map(item -> {
                TbDict tbDict = JSON.parseObject(item.toString(), TbDict.class);
                return tbDict;
            }).collect(Collectors.toList());

            return R.OK(tbDictList);
        }
        List<TbDict> tbDictList = tbDictMapper.selectList(
                new LambdaQueryWrapper<TbDict>().eq(TbDict::getDictType, typeId)
        );
        return R.OK(tbDictList);
    }

    @Override
    public R addProd(TbProd tbProd) {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }
        String userName = TokenUtil.userName(token);

        TbProd prod = tbProdMapper.selectOne(
                new LambdaQueryWrapper<TbProd>().eq(TbProd::getProdName, tbProd.getProdName())
        );
        if(prod != null){
            return R.ERROR(500,"该商品已经存在");
        }

        tbProd.setCreateBy(userName);
        tbProd.setCreateTime(new Date());

        tbProdMapper.insert(tbProd);

        return R.OK();
    }

    @Override
    public R addProdAtta(TbProdAtta tbProdAtta) {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }
        String userName = TokenUtil.userName(token);

        TbProd prod = tbProdMapper.selectById(tbProdAtta.getProdId());
        if(prod == null){
            return R.ERROR(404,"商品不存在");
        }

        tbProdAtta.setCreateBy(userName);
        tbProdAtta.setCreateTime(new Date());

        tbProdAttaMapper.insert(tbProdAtta);
        return R.OK();
    }

    @Override
    public R getProdInfoList() {
        List<TbProdInfo> tbProdInfoList = tbProdInfoMapper.selectList(null);
        return R.OK(tbProdInfoList);
    }


    @Override
    public R getProdInfoPage(PageInfoVo pageInfoVo) {
        Page<TbProdInfo> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        Page<TbProdInfo> tbProdInfoPage = tbProdInfoMapper.selectPage(page, null);
        return R.OK(tbProdInfoPage);
    }

    @Override
    public R addProdInfo(TbProdInfo tbProdInfo) {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }
        String userName = TokenUtil.userName(token);

        TbProdInfo prodInfo = tbProdInfoMapper.selectOne(
                new LambdaQueryWrapper<TbProdInfo>().eq(TbProdInfo::getProdSku, tbProdInfo.getProdSku())
                        .or()
                        .eq(TbProdInfo::getProdName,tbProdInfo.getProdName())
        );

        if(prodInfo != null){
            return R.ERROR(500,"商品信息已经存在");
        }

        tbProdInfo.setProdId(tbProdInfo.getProdId());
        tbProdInfo.setCreateBy(userName);
        tbProdInfo.setCreateTime(new Date());

        tbProdInfoMapper.insert(tbProdInfo);
        return R.OK();
    }


}




